package com.kinglone.back.user.realm;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.kinglone.back.user.model.User;
import com.kinglone.back.user.service.UserService;

/**
 * 自定义realm
 * @author Administrator
 *
 */
public class MyRealm extends AuthorizingRealm{

	@Resource
	private UserService userService;
	
	/**
	 * 为当限前登录的用户授予角色和权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}

	/**
	 * 验证当前登录的用户
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
	
		 UsernamePasswordToken token = (UsernamePasswordToken) authcToken;  
		 String accountName = token.getUsername();  
		 System.out.println("------accountName:"+accountName);
		
		if(!StringUtils.isEmpty(accountName)){  
            User user = userService.getByUserName(accountName);  
            if(user != null){ 
            SecurityUtils.getSubject().getSession().setAttribute("currentUser", user); // 当前用户信息存到session中
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), "xx");
            return authenticationInfo;
            }  
        }  	
			return null;	
	}

}
